package com.gimi.cloud.bbp.task.queue;

import com.alibaba.fastjson.JSON;
import com.gimi.cloud.bbp.commonService.mq.enume.QueueConstant;
import com.gimi.cloud.bbp.dto.task.ScheduleJobDTO;
import com.gimi.cloud.bbp.task.service.ScheduleJobService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消息接受者
 *
 * @author wbj
 * @version 1.0
 * @Description
 * @create 2018-01-10
 **/
@Component
public class QueueReciver {
    private static  final Logger logger = LoggerFactory.getLogger(QueueReciver.class);
    private ScheduleJobService scheduleJobService;

    @Autowired
    public QueueReciver(ScheduleJobService scheduleJobService) {
        this.scheduleJobService = scheduleJobService;
    }

    /**
     * 更改queue状态
     * @param message
     * @param channel
     * @param scheduleJob
     */
    @RabbitListener(queues = {QueueConstant.TASK_QUEUE_NAME})
    public  void changeQueueStatus(Message message, Channel channel, ScheduleJobDTO scheduleJob) throws IOException{
        logger.info("======接收消息,类型为："+scheduleJob.getChangeQueueType()+"；详情："+JSON.toJSONString(scheduleJob));
        try {
            scheduleJob.setChangeQueueType(null == scheduleJob.getChangeQueueType()?"":scheduleJob.getChangeQueueType());
            switch (scheduleJob.getChangeQueueType()){
                //新增定时任务
                case "create":
                    scheduleJobService.createScheduleJob(scheduleJob);
                    break;
                //更新定时任务
                case "update":
                    scheduleJobService.updateScheduleJob(scheduleJob);
                    break;
                //删除定时任务
                case "delete":
                    scheduleJobService.deleteScheduleJob(scheduleJob);
                    break;
                //执行定时任务
                case "run":
                    scheduleJobService.runScheduleJob(scheduleJob);
                    break;
                //暂停定时任务
                case "pause":
                    scheduleJobService.pauseScheduleJob(scheduleJob);
                    break;
                //恢复定时任务
                case "resume":
                    scheduleJobService.resumeScheduleJob(scheduleJob);
                    break;
                default:
                    logger.info("未知的定时任务队列消息:"+scheduleJob.getChangeQueueType());
                    break;
            }
        }catch (Exception e) {
            //此处定时任务不标记为取消，直接标记为完成，避免重复执行或启用等操作
            e.printStackTrace();
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
}
